package com.sigmatrix.h5.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 
 *@ClassName: BaseController
 *@Description: controller基类
 *@author MH
 *@date 2017年11月7日 上午11:17:36
 */
public class BaseController {
	
	protected Logger logger = Logger.getLogger(this.getClass());
	
	private final String HEADER_X_FORWARDED_FOR = "x-forwarded-for";
	
	private final String HEADER_PROXY_CLIENT_IP = "Proxy-Client-IP";
	
	private final String HEADER_WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
	
	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;
	protected <T> Result<T> ok(T data){
		return Result.ok(data);
	}
	
	protected <T> Result<T> error(String message){
		return Result.error(message);
	}
	/**
	 * 
	 *@Title: remoteAddr
	 *@Description: 获取客户端IP
	 *@return String
	 *@author MH
	 *@date 2017年9月30日 下午12:55:14
	 *@param request
	 *@return
	 */
	protected String remoteAddr(){
		
		String ip = request.getHeader(HEADER_X_FORWARDED_FOR);
		
		if(StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader(HEADER_PROXY_CLIENT_IP);
		}
		if(StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader(HEADER_WL_PROXY_CLIENT_IP);
		}
		if(StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
		}
		logger.info(String.format("ip chain = %s",ip));
		return ip.split(",")[0];
	}
}
